<!--
 * @Author: daidai
 * @Date: 2022-02-28 16:16:42
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-07-20 17:57:11
 * @FilePath: \web-pc\src\pages\big-screen\view\indexs\left-center.vue
-->
<template>
  <div class="college-overview" v-if="pageflag">
    <div class="scroll-container" ref="scrollContainer">
      <div class="college-list" ref="collegeList">
        <div
          class="college-item"
          v-for="(college, index) in collegeList"
          :key="index"
        >
          <div class="college-name">{{ college.name }}</div>
          <div class="progress-container">
            <el-progress
              :percentage="college.reportRate"
              :color="college.color"
              :stroke-width="12"
              :show-text="true"
              :format="formatPercentage"
            ></el-progress>
          </div>
          <div class="college-stats">
            <span class="registered-count"
              >{{ college.registered }}/{{ college.total }}</span
            >
          </div>
        </div>
      </div>
    </div>
  </div>
  <Reacquire v-else @onclick="processReportedData" style="line-height: 200px">
    重新获取
  </Reacquire>
</template>

<script>
  export default {
    data() {
      return {
        pageflag: true,
        scrollTimer: null,
        collegeList: [],
        currentScrollTop: 0,
        scrollDirection: 1, // 1向下滚动，-1向上滚动
        // 颜色数组，用于为不同学院分配颜色
        colors: [
          "#00fdfa",
          "#07f7a8",
          "#e3b337",
          "#f5023d",
          "#3b82f6",
          "#8b5cf6",
          "#10b981",
          "#f59e0b",
          "#ef4444",
          "#8b5cf6",
          "#06b6d4",
          "#84cc16",
          "#f97316",
          "#ec4899",
          "#6366f1",
          "#14b8a6",
          "#eab308",
          "#dc2626",
          "#9333ea",
        ],
      };
    },
    props: {
      allStudentsData: {
        type: Object,
        default: () => ({}),
      },
      reportedStudentsData: {
        type: Object,
        default: () => ({}),
      },
    },
    watch: {
      reportedStudentsData: {
        handler(newData) {
          if (newData && Object.keys(newData).length > 0) {
            this.processReportedData();
          }
        },
        immediate: true,
        deep: true,
      },
      allStudentsData: {
        handler(newData) {
          // 当报到数据不可用时，使用学生总览数据
          if (
            (!this.reportedStudentsData ||
              Object.keys(this.reportedStudentsData).length === 0) &&
            newData &&
            Object.keys(newData).length > 0
          ) {
            this.processReportedData();
          }
        },
        immediate: true,
        deep: true,
      },
    },
    created() {
      this.processReportedData();
    },
    mounted() {
      this.$nextTick(() => {
        this.startAutoScroll();
      });
    },
    beforeDestroy() {
      this.clearScrollTimer();
    },
    methods: {
      formatPercentage(percentage) {
        return `${percentage}%`;
      },
      clearScrollTimer() {
        if (this.scrollTimer) {
          clearInterval(this.scrollTimer);
          this.scrollTimer = null;
        }
      },

      // 处理报到统计数据
      processReportedData() {
        this.pageflag = true;

        try {
          // 优先使用报到统计数据 - 现在直接是data字段的内容
          if (
            this.reportedStudentsData &&
            this.reportedStudentsData.collegeStats
          ) {
            // 从collegeStats中解析各学院报到数据
            const collegeStats = this.reportedStudentsData.collegeStats;

            this.collegeList = Object.values(collegeStats).map(
              (item, index) => {
                return {
                  name: item.collegeName,
                  reportRate: Math.round(item.enrollmentRate * 10) / 10,
                  registered: item.enrolledStudents,
                  total: item.totalStudents,
                  color: this.getColorByRate(item.enrollmentRate, index),
                };
              }
            );

            // 按报到率排序，报到率高的在前
            this.collegeList.sort((a, b) => b.reportRate - a.reportRate);

            console.log("处理后的学院报到列表:", this.collegeList);
          } else {
            console.warn("报到统计数据不可用，尝试使用备用数据");
            this.handleFallbackData();
          }

          // 重新启动滚动
          this.$nextTick(() => {
            this.startAutoScroll();
          });
        } catch (error) {
          console.error("处理学院报到统计数据失败:", error);
          this.handleFallbackData();
        }
      },

      // 根据报到率动态分配颜色
      getColorByRate(rate, index) {
        if (rate >= 80) {
          return "#56B557"; // 绿色 - 高报到率
        } else if (rate >= 50) {
          return "#FFA726"; // 橙色 - 中等报到率
        } else if (rate >= 20) {
          return "#FF6B6B"; // 红色 - 低报到率
        } else {
          return "#666666"; // 灰色 - 极低或无报到
        }
      },

      // 备用数据处理 - 使用传入的学生总览数据
      handleFallbackData() {
        if (
          this.allStudentsData &&
          this.allStudentsData.academic_distribution &&
          this.allStudentsData.academic_distribution.departments &&
          Array.isArray(this.allStudentsData.academic_distribution.departments)
        ) {
          console.log("使用备用学生总览数据:", this.allStudentsData);

          // 从allStudentsData中解析各学院数据（但报到率为0）
          const departments =
            this.allStudentsData.academic_distribution.departments;

          this.collegeList = departments.map((item, index) => {
            return {
              name: item.department,
              reportRate: 0, // 备用数据报到率为0
              registered: 0,
              total: item.count,
              color: this.colors[index % this.colors.length], // 使用默认颜色
            };
          });

          console.log("处理后的备用学院列表:", this.collegeList);
        } else {
          console.log("暂无任何学院数据");
          this.collegeList = [];
        }

        // 重新启动滚动
        this.$nextTick(() => {
          this.startAutoScroll();
        });
      },

      // 启动自动滚动
      startAutoScroll() {
        this.clearScrollTimer();

        const container = this.$refs.scrollContainer;
        const list = this.$refs.collegeList;

        if (!container || !list) return;

        const containerHeight = container.clientHeight;
        const listHeight = list.scrollHeight;

        // 如果内容高度小于等于容器高度，不需要滚动
        if (listHeight <= containerHeight) {
          return;
        }

        const maxScrollTop = listHeight - containerHeight;

        this.scrollTimer = setInterval(() => {
          this.currentScrollTop += this.scrollDirection * 1; // 每次滚动1px

          // 到达底部时，改变滚动方向
          if (this.currentScrollTop >= maxScrollTop) {
            this.scrollDirection = -1;
            this.currentScrollTop = maxScrollTop;
          }

          // 到达顶部时，改变滚动方向
          if (this.currentScrollTop <= 0) {
            this.scrollDirection = 1;
            this.currentScrollTop = 0;
          }

          container.scrollTop = this.currentScrollTop;
        }, 50); // 每50ms滚动一次，可调整速度
      },
    },
  };
</script>

<style lang="scss" scoped>
  .college-overview {
    width: 100%;
    height: 100%;

    .scroll-container {
      width: 100%;
      height: calc(100% - 20px); // 设置固定高度，可根据实际需要调整
      overflow: hidden; // 隐藏超出部分
      position: relative;

      .college-list {
        width: 100%;

        .college-item {
          display: flex;
          align-items: center;
          margin-bottom: 18px;
          padding: 0 10px;
          position: relative;

          .college-name {
            width: 140px;
            font-size: 15px;
            color: #ffffff;
            text-align: right;
            padding-right: 15px;
            flex-shrink: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.2;
          }

          .progress-container {
            flex: 1;
            margin-right: 15px;
          }

          .college-stats {
            width: 80px;
            flex-shrink: 0;
            text-align: right;

            .registered-count {
              font-size: 12px;
              color: rgba(255, 255, 255, 0.8);
              font-weight: 500;
              line-height: 1.2;
            }
          }
        }
      }
    }
  }

  // 全局样式覆盖
  ::v-deep .el-progress {
    .el-progress-bar {
      .el-progress-bar__outer {
        background-color: rgba(255, 255, 255, 0.1) !important;
        border-radius: 6px !important;
      }

      .el-progress-bar__inner {
        border-radius: 6px !important;
        transition: all 0.3s ease !important;
      }
    }

    .el-progress__text {
      color: #ffffff !important;
      font-size: 13px !important;
      font-weight: 600 !important;
      margin-left: 8px !important;
    }
  }
</style>
